package com.ldk.api;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.base.framework.util.ConfigUtil;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.PropertiesUtil;
import com.ldk.base.framework.util.cache.RedisUtil;
import com.unionpay.sdk.SDKConfig;

/**
 * 请求拦截器
 * @author xiangwl
 */
public class RequestHandlerInterceptor implements HandlerInterceptor {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//注册系统配置
		if(request.getSession().getAttribute("configs") == null){
			try{
				String cfgPath = Consts.DEBUG ? this.getClass().getResource("/").getPath() + "/config_debug.properties" :
												this.getClass().getResource("/").getPath() + "/config.properties";
				Properties cfgProps = PropertiesUtil.read(cfgPath);
				request.getSession().setAttribute("configs", cfgProps);
				//设置配置属性到系统属性中
				ConfigUtil.GetInstance().setConfig(cfgProps);
			}
			catch(Exception e){
				logger.error(e.getMessage());
			}
		}
		//redis配置
		if(request.getSession().getAttribute("redis") == null){
			try{
				String cfgPath = Consts.DEBUG ? this.getClass().getResource("/").getPath() + "/redis_debug.properties" : 
												this.getClass().getResource("/").getPath() + "/redis.properties";
				Properties cfgProps = PropertiesUtil.read(cfgPath);
				request.getSession().setAttribute("redis", cfgProps);
				//redis参数配置
				String startup = PropertiesUtil.getProperty(cfgProps, "startup");
				Boolean useRedis = ConvertUtil.parseBoolean(startup);
				String redisHost = PropertiesUtil.getProperty(cfgProps, "redisHost");
				String strPort  = PropertiesUtil.getProperty(cfgProps, "redisPort");
				int redisPort = ConvertUtil.parseInt(strPort, 6379);
				//配置redis
				RedisUtil.getInstance().config(redisHost, redisPort, useRedis);
			}
			catch(Exception e){
				logger.error(e.getMessage());
			}
		}
		//推送配置
		//请使用JPushDispatcherBean

		//加载银联配置
		SDKConfig.getConfig().loadPropertiesFromSrc();// 从classpath加载acp_sdk.properties文件
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
